package com.wxblockchain.prometheum;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.wxblockchain.prometheum.ui.account.AccountFragment;
import com.wxblockchain.prometheum.ui.market.MarketFragment;
import com.wxblockchain.prometheum.ui.position.PositionFragment;

public class FragmentSwitchTool {
    private FragmentManager fragmentManager;
    private int containerId;

    private Fragment marketFragment;
    private Fragment positionFragment;
    private Fragment accountFragment;

    private Fragment cacheFragment;


    public FragmentSwitchTool(FragmentManager fragmentManager, int containerId) {
        this.fragmentManager = fragmentManager;
        this.containerId = containerId;
    }

    public void changeTab(String label) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (cacheFragment != null) {
            fragmentTransaction.hide(cacheFragment);
        }

        switch (label) {
            case "Market":
                if (marketFragment == null) {
                    marketFragment = new MarketFragment();

                    fragmentTransaction.add(containerId,marketFragment,"Market");
                } else {
                    fragmentTransaction.show(marketFragment);
                }
//                fragmentTransaction.addToBackStack("Market");

                this.cacheFragment = marketFragment;

                break;

            case "Position":
                if (positionFragment == null) {
                    positionFragment = new PositionFragment();

                    fragmentTransaction.add(containerId,positionFragment,"Position");
                } else {
                    fragmentTransaction.show(positionFragment);
                }
//                fragmentTransaction.addToBackStack("Position");

                this.cacheFragment = positionFragment;

                break;

            case "Account":
                if (accountFragment == null) {
                    accountFragment = new AccountFragment();

                    fragmentTransaction.add(containerId,accountFragment,"Account");
                } else {
                    fragmentTransaction.show(accountFragment);
                }
//                fragmentTransaction.addToBackStack("Account");


                this.cacheFragment = accountFragment;

                break;
        }

//        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commitAllowingStateLoss();
    }

}
